package com.zycfc.zsf.boot.mq.rabbitmq.producer;

import org.springframework.amqp.rabbit.core.*;
import com.zycfc.zsf.boot.mq.rabbitmq.converter.*;
import org.springframework.amqp.rabbit.support.*;
import com.zycfc.zsf.boot.mq.rabbitmq.retry.*;
import org.springframework.util.*;
import java.io.*;
import com.zycfc.zsf.boot.mq.rabbitmq.handler.*;
import org.springframework.amqp.*;
import com.zycfc.zsf.boot.mq.rabbitmq.destinations.*;
import com.zycfc.zsf.boot.core.common.*;
import com.zycfc.zsf.boot.common.context.*;
import com.zycfc.zsf.boot.util.text.*;
import com.zycfc.zsf.boot.util.json.*;
import org.springframework.amqp.support.converter.*;
import java.util.*;
import org.springframework.amqp.core.*;
import com.zycfc.zsf.boot.mq.rabbitmq.type.*;
import org.slf4j.*;
import java.lang.reflect.*;

public final class SimpleMessageProducer implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback
{
    private static final Logger log;
    private static final JsonMessageConverter messageConverter;
    private final RabbitTemplate rabbitTemplate;
    private final AmqpAdmin amqpAdmin;
    private MessageProducerCallback callback;
    private RetryCache retryCache;
    private String namespace;
    private String appName;
    private DbProcessProvider dbProcessProvider;
    
    public SimpleMessageProducer(final RabbitTemplate rabbitTemplate, final AmqpAdmin amqpAdmin, final String namespace, final DbProcessProvider dbProcessProvider) {
        this.amqpAdmin = amqpAdmin;
        (this.rabbitTemplate = rabbitTemplate).setMessageConverter((MessageConverter)SimpleMessageProducer.messageConverter);
        this.rabbitTemplate.setConfirmCallback((RabbitTemplate.ConfirmCallback)this);
        this.rabbitTemplate.setReturnCallback((RabbitTemplate.ReturnCallback)this);
        this.namespace = namespace;
        this.dbProcessProvider = dbProcessProvider;
    }
    
    public void confirm(final CorrelationData correlationData, final boolean ack, final String cause) {
        if (ack) {
            if (SimpleMessageProducer.log.isDebugEnabled()) {
                SimpleMessageProducer.log.debug("\u6d88\u606f {} \u5df2\u7ecf\u6210\u529f\u53d1\u9001\u5230\u4ea4\u6362\u5668\u4e2d", (Object)correlationData.getId());
            }
            if (null != this.retryCache) {
                this.retryCache.del(correlationData.getId());
            }
        }
        else {
            if (SimpleMessageProducer.log.isWarnEnabled()) {
                SimpleMessageProducer.log.warn("\u6d88\u606f {} \u56e0{} \u672a\u80fd\u53d1\u9001\u5230\u4ea4\u6362\u5668\u4e2d", (Object)correlationData.getId(), (Object)cause);
            }
            if (null != this.retryCache) {
                final MessageCache messageCache = this.retryCache.get(correlationData.getId());
                if (messageCache != null) {
                    this.saveDbError(messageCache.getExchangeName(), messageCache.getMessage(), "confirm");
                }
            }
        }
        if (null != this.callback) {
            this.callback.onConfirm(correlationData.getId(), ack, cause);
        }
    }
    
    private void saveDbError(final String queueName, final Message message, final String messageType) {
        final MessageProperties messageProperties = message.getMessageProperties();
        final Date optTime = ObjectUtils.isEmpty((Object)messageProperties) ? new Date() : messageProperties.getTimestamp();
        String msg = "";
        try {
            msg = new String(message.getBody(), "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            SimpleMessageProducer.log.error("\u8f6c\u6362\u5f02\u5e38", (Throwable)e);
        }
        this.saveDbError(messageProperties.getMessageId(), queueName, msg, optTime, messageType, messageProperties.getCorrelationId());
    }
    
    private void saveDbError(final String messageId, final String queueName, final String messageStr, final Date optTime, final String messageType, final String correlationId) {
        final TSysMqProducerErrs err = new TSysMqProducerErrs(this.appName, messageId, queueName, messageStr, optTime, messageType);
        err.setCorrelationId(correlationId);
        this.dbProcessProvider.saveProducerErrLog(err);
    }
    
    public void returnedMessage(final Message message, final int replyCode, final String replyText, final String exchange, final String routingKey) {
        final Object messageData = message.getBody();
        final MessageProperties messageProperties = message.getMessageProperties();
        if (SimpleMessageProducer.log.isWarnEnabled()) {
            SimpleMessageProducer.log.warn("\u6d88\u606f:{} \u53d1\u9001\u5230\u4ea4\u6362\u5668:{}\u540e\uff0c\u65e0\u6cd5\u6839\u636e\u81ea\u8eab\u7684\u7c7b\u578b\u548c\u8def\u7531\u952e:{}\u627e\u5230\u4e00\u4e2a\u7b26\u5408\u6761\u4ef6\u7684\u961f\u5217\uff0creplyCode\uff1a{}, replyText {}.\uff0c\u8be6\u7ec6\u4fe1\u606f\uff1a{}", new Object[] { messageData, exchange, routingKey, replyCode, replyText, messageProperties });
        }
        String messageId = null;
        if (null != messageProperties) {
            messageId = messageProperties.getMessageId();
            this.saveDbError(exchange, message, "return");
        }
        if (null != this.callback) {
            this.callback.onReturned(messageId, messageData, replyCode, replyText, exchange, routingKey);
        }
    }
    
    private Message convertMessageIfNecessary(final Object object, MessageProperties messageProperties) {
        if (object instanceof Message) {
            return (Message)object;
        }
        if (null == messageProperties) {
            messageProperties = new MessageProperties();
        }
        return this.getRequiredMessageConverter().toMessage(object, messageProperties);
    }
    
    private MessageConverter getRequiredMessageConverter() throws IllegalStateException {
        final MessageConverter converter = this.rabbitTemplate.getMessageConverter();
        if (converter == null) {
            throw new AmqpIllegalStateException("No 'messageConverter' specified. Check configuration of RabbitTemplate.");
        }
        return converter;
    }
    
    public void sendMessage(final IDestination destination, final Object message, MessageProperties messageProperties) throws Exception {
        String messageId = null;
        if (null != messageProperties) {
            messageId = messageProperties.getMessageId();
        }
        if (null == messageId || messageId.isEmpty()) {
            messageId = UUID.randomUUID().toString().replaceAll("-", "");
        }
        final String routingKey = this.namespace + "." + destination.getRoutingKey();
        if (null != routingKey && routingKey.indexOf(42) != -1 && routingKey.indexOf(35) != -1) {
            throw new Exception("\u8def\u7531\u952e\"" + routingKey + "\"\u4e2d\u5305\u542b\u6709*\u6216#\u5b57\u7b26!");
        }
        String correlationId = "";
        try {
            SimpleMessageProducer.log.debug("sendMessage-- messageId is [{}]", (Object)messageId);
            final Message sendMessage = this.convertMessageIfNecessary(message, messageProperties);
            messageProperties = sendMessage.getMessageProperties();
            if (null != messageProperties) {
                if (null == messageProperties.getMessageId()) {
                    messageProperties.setMessageId(messageId);
                }
                if (null == messageProperties.getCorrelationId()) {
                    messageProperties.setCorrelationId(messageId);
                }
                messageProperties.setAppId(this.appName);
                messageProperties.setTimestamp(new Date());
                if (EnvNameEnum.sit.name().equals(this.namespace) || EnvNameEnum.sit830.name().equals(this.namespace) || EnvNameEnum.u3.name().equals(this.namespace)) {
                    final String openScene = ZsfRootContext.get("openScene");
                    if (StringUtils.isNotEmpty(openScene)) {
                        messageProperties.setHeader("openScene", (Object)openScene);
                    }
                    final String openBaffle = ZsfRootContext.get("openBaffle");
                    if (StringUtils.isNotEmpty(openBaffle)) {
                        messageProperties.setHeader("openBaffle", (Object)openBaffle);
                    }
                    SimpleMessageProducer.log.debug("sendMessage--openScene:{}-openBaffle:{}", (Object)openScene, (Object)openBaffle);
                }
            }
            final String exchangeName = this.namespace + "." + destination.exchange().getName();
            SimpleMessageProducer.log.debug("routingKey=" + routingKey + ",exchangeName=" + exchangeName);
            MessageCache messageCache = null;
            if (null != this.retryCache) {
                messageCache = this.retryCache.add(messageId, exchangeName, routingKey, sendMessage);
            }
            correlationId = this.doSendMessage(exchangeName, routingKey, sendMessage, messageId);
            if (null != messageCache) {
                messageCache.setSended(true);
            }
        }
        catch (Exception e) {
            SimpleMessageProducer.log.error(e.getMessage(), (Throwable)e);
            if (null != this.retryCache) {
                this.retryCache.del(messageId);
            }
            if (destination.getSaveErrFlag()) {
                final String queueName = this.namespace + "." + destination.exchange().getName();
                final Date optTime = ObjectUtils.isEmpty((Object)messageProperties) ? new Date() : messageProperties.getTimestamp();
                this.saveDbError(messageProperties.getMessageId(), queueName, JsonUtils.objectToJson(message), optTime, "send", correlationId);
            }
            throw e;
        }
    }
    
    public String doSendMessage(final String exchangeName, final String routingKey, final Message message, final String messageId) {
        final CorrelationData correlationData = new CorrelationData(messageId);
        this.rabbitTemplate.send(exchangeName, routingKey, message, correlationData);
        return correlationData.getId();
    }
    
    public String doSendMessageResume(final String queueName, final String requestData, final String messageId) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty((Object)queueName) || !queueName.contains(".") || queueName.split("\\.").length != 3) {
            throw new Exception("\u751f\u4ea7\u8005\u91cd\u8bd5\u961f\u5217\u540d\u79f0\"" + queueName + "\"\u683c\u5f0f\u9519\u8bef!");
        }
        SimpleMessageProducer.log.debug("resume sendMessage-- messageId is [{}], data is [{}] ", (Object)messageId, (Object)requestData);
        final String routingKey = queueName.substring(0, queueName.indexOf(".") + 1);
        final Message message = this.convertJsonMessage(requestData, null, messageId);
        return this.doSendMessage(queueName, routingKey, message, messageId);
    }
    
    private Message convertJsonMessage(final String requestData, MessageProperties messageProperties, final String messageId) {
        if (null == messageProperties) {
            messageProperties = new MessageProperties();
        }
        try {
            final byte[] bytes = requestData.getBytes("UTF-8");
            if (bytes != null) {
                messageProperties.setContentLength((long)bytes.length);
            }
            messageProperties.setContentType("application/json");
            messageProperties.setContentEncoding("UTF-8");
            messageProperties.setMessageId(messageId);
            messageProperties.setCorrelationId(messageId);
            messageProperties.setAppId(this.appName);
            messageProperties.setTimestamp(new Date());
            return new Message(bytes, messageProperties);
        }
        catch (Exception e) {
            SimpleMessageProducer.log.error(e.getMessage(), (Throwable)e);
            throw new MessageConversionException("failed to convert to rabbitmq json Message", (Throwable)e);
        }
    }
    
    public void sendMessage(final IDestination destination, final Object message) throws Exception {
        this.sendMessage(destination, message, null);
    }
    
    public void sendMessageToJson(final IDestination destination, final Object message) throws Exception {
        this.sendMessageToJson(null, destination, message);
    }
    
    public void sendMessageToJson(final String flowId, final IDestination destination, final Object message) throws Exception {
        this.sendMessageToJson(flowId, destination, message, null);
    }
    
    public void sendMessageToJson(final String flowId, final IDestination destination, final Object message, final Integer priority) throws Exception {
        final MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType("application/json");
        messageProperties.setCorrelationId(flowId);
        if (priority != null && priority > 0) {
            messageProperties.setPriority(priority);
        }
        final Map<String, Object> arguments = (Map<String, Object>)destination.exchange().getArguments();
        if (arguments != null && arguments.size() > 0) {
            arguments.remove("x-match");
            for (final String key : arguments.keySet()) {
                final Object value = arguments.get(key);
                messageProperties.setHeader(key, value);
            }
        }
        this.sendMessage(destination, message, messageProperties);
    }
    
    public void sendMessageToString(final String flowId, final IDestination destination, final String message) throws Exception {
        final MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType("text/plain");
        messageProperties.setCorrelationId(flowId);
        this.sendMessage(destination, message, messageProperties);
    }
    
    public void sendMessageToString(final IDestination destination, final String message) throws Exception {
        this.sendMessageToString(null, destination, message);
    }
    
    public void declareAll(final IDestination destination) {
        destination.resetName(this.namespace, destination);
        if (!destination.isDefaultExchange()) {
            this.amqpAdmin.declareExchange((Exchange)destination.exchange());
        }
        if (!ExchangeType.FANOUT.equals(destination.exchangeType())) {
            this.amqpAdmin.declareQueue(destination.queue());
            this.amqpAdmin.declareBinding(destination.binding());
        }
    }
    
    public void setCallback(final MessageProducerCallback callback) {
        this.callback = callback;
    }
    
    public void setRetryCache(final RetryCache retryCache) {
        this.retryCache = retryCache;
    }
    
    public void setNamespace(final String namespace) {
        this.namespace = namespace;
    }
    
    public void setAppName(final String appName) {
        this.appName = appName;
    }
    
    public void setDbProcessProvider(final DbProcessProvider dbProcessProvider) {
        this.dbProcessProvider = dbProcessProvider;
    }
    
    public RabbitTemplate getRabbitTemplate() {
        return this.rabbitTemplate;
    }
    
    public AmqpAdmin getAmqpAdmin() {
        return this.amqpAdmin;
    }
    
    public MessageProducerCallback getCallback() {
        return this.callback;
    }
    
    public RetryCache getRetryCache() {
        return this.retryCache;
    }
    
    public String getNamespace() {
        return this.namespace;
    }
    
    public String getAppName() {
        return this.appName;
    }
    
    public DbProcessProvider getDbProcessProvider() {
        return this.dbProcessProvider;
    }
    
    static {
        log = LoggerFactory.getLogger((Class)SimpleMessageProducer.class);
        messageConverter = new JsonMessageConverter(null);
    }
}
